package com.eobard.utils;

import com.eobard.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Eobard_Thawne
 * @version 1.0
 * @date 2022/8/6 -20:24
 */

@Data
@ConfigurationProperties(prefix = "jwt")
@Component
public class JwtUtils {
    //密钥
    private String secret;
    // 过期时间毫秒:默认设置为30分钟
    private Long expiration;

    /**
     *  从自定义payload中生成令牌
     */
    private String generateToken(Map<String, Object> payload) {
        //令牌过期时间=当前时间+过期时间
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder()
                    .setClaims(payload)              //设置payload信息:存放实际需要传递的数据
                    .setExpiration(expirationDate)  //设置令牌过期时间
                    .signWith(SignatureAlgorithm.HS512, secret)//设置秘钥
                    .compact();
    }

    /**
     * 生成令牌
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> payload  = new HashMap<>(2);
        payload.put(Claims.SUBJECT, userDetails.getUsername());     //设置主体
        payload.put(Claims.ISSUED_AT, new Date());                  //设置签发时间
        return generateToken(payload);
    }

    /**
     * 从令牌中获取payload信息
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims =Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }


    /**
     * 从令牌中获取用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     */
    public Boolean isTokenExpired(String token) {
        Claims claims = getClaimsFromToken(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 刷新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT, new Date());       //将获取到的token重新设置签发时间
            refreshedToken = generateToken(claims);         //再次生成token
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证令牌
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        User user = (User) userDetails;
        String username = getUsernameFromToken(token);//获取token中的用户名
        //判断token的用户名和数据库的用户名是否一致&&token是否过期
        return (username.equals(user.getUsername()) && !isTokenExpired(token));
    }

    /**
     * 获取请求头的token信息
     */
    public String getTokenFromRequest(HttpServletRequest request){
        //获取请求头的token
        String token = request.getHeader("token");
        //如果请求头没有token,尝试从请求参数中获取
        if (ObjectUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }
        return token;
    }
}
